package cn.finalteam.galleryfinal;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;

import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.toolsfinal.DateUtils;
import cn.finalteam.toolsfinal.DeviceUtils;
import cn.finalteam.toolsfinal.FileUtils;
import cn.finalteam.toolsfinal.Logger;
import cn.finalteam.toolsfinal.StringUtils;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;

public class PhotoTakeActivity extends PhotoBaseActivity{
	private Uri mTakePhotoUri;
    private int mPickMode = GalleryHelper.SINGLE_IMAGE;
    private boolean mCrop;
    //是否需要刷新相册
    private boolean mHasRefreshGallery = false;
    private Handler mHanlder = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if ( msg.what == 1000 ) {
                PhotoInfo photoInfo = (PhotoInfo) msg.obj;
//                takeRefreshGallery(photoInfo);
                ArrayList<PhotoInfo> photoList = new ArrayList();
                photoList.add(photoInfo);
                resultMuti(photoList);
            } 
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        if (!DeviceUtils.existSDCard()) {
            toast("没有SD卡不能拍照呢~");
            return;
        }

        File takePhotoFolder = null;
        if (StringUtils.isEmpty(mPhotoTargetFolder)) {
            takePhotoFolder = new File(Environment.getExternalStorageDirectory(),
                    "/DCIM/" + GalleryHelper.TAKE_PHOTO_FOLDER);
        } else {
            takePhotoFolder = new File(mPhotoTargetFolder);
        }

        File toFile = new File(takePhotoFolder, "IMG" + DateUtils.format(new Date(), "yyyyMMddHHmmss") + ".jpg");
        boolean suc = FileUtils.makeFolders(toFile);
        Logger.d("create folder=" + toFile.getAbsolutePath());
        if (suc) {
            mTakePhotoUri = Uri.fromFile(toFile);
            Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mTakePhotoUri);
            startActivityForResult(captureIntent, GalleryHelper.TAKE_REQUEST_CODE);
        }
        
    }
    
    @Override
    protected void takeResult(PhotoInfo photoInfo) {

        Message message = mHanlder.obtainMessage();
        message.obj = photoInfo;
        message.what = 1000;

        if ( mPickMode == GalleryHelper.SINGLE_IMAGE ) { //单选
            if ( mCrop ) {//裁剪
                mHasRefreshGallery = true;
                toPhotoCrop(photoInfo);
            } else {
                resultSingle(photoInfo);
            }
            mHanlder.sendMessageDelayed(message, 100);
        }

    }
    
}
